package com.mayo.series;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;

import com.mayo.series.alphabetic.ExampleContactListView;
import com.mayo.series.alphabetic.SerieAdapter;
import com.mayo.series.alphabetic.SerieItem;
import com.mayo.series.alphabetic.SerieItemInterface;
import com.mayo.series.comun.BaseActivity;
import com.mayo.series.comun.ComunUtilidades;
import com.mayo.series.json.objects.SerieObject;

public class ListadoSeriesActivity extends BaseActivity implements TextWatcher {

	private ExampleContactListView listview;
	private List<SerieObject> listaSeries = new ArrayList<SerieObject>();
	
	private EditText searchBox;
	private String searchString;
	
	private Object searchLock = new Object();
	boolean inSearchMode = false;
	
	private final static String TAG = "com.mayo.series.alphabetic";
	
	List<SerieItemInterface> contactList;
	List<SerieItemInterface> filterList;
	private SearchListTask curSearchTask = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contact_list);
        
		actionBar.setTitle(R.string.tit_listado_series);
		//actionBar.setHomeLogo(R.drawable.ic_launcher);
		
		filterList = new ArrayList<SerieItemInterface>();
		
		listview = (ExampleContactListView) this.findViewById(R.id.listview);
		listview.setFastScrollEnabled(true);
		
		// use this to process individual clicks
		// cannot use OnClickListener as the touch event is overrided by IndexScroller
		// use last touch X and Y if want to handle click for an individual item within the row
		listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView parent, View v, int position,
					long id) {
					List<SerieItemInterface> searchList = inSearchMode ? filterList : contactList ;
					//Toast.makeText(ListadoSeriesActivity.this, "User image is clicked ( " + searchList.get(position).getItemForIndex()  + ")", Toast.LENGTH_SHORT).show();
					SerieItem item = (SerieItem) parent.getItemAtPosition(position);
					SerieObject serie = ComunUtilidades.getItemFromId(item.getId(), listaSeries);
					Intent intent = new Intent(getApplicationContext(), DetalleSerieActivity.class);
					Bundle contenedor=new Bundle();
					contenedor.putParcelable("serie", serie);
					intent.putExtras(contenedor);
					startActivity(intent);
			}
		});
		
		
		searchBox = (EditText) findViewById(R.id.input_search_query);
		searchBox.addTextChangedListener(this);
		
		new LoadAlphabeticSeries().execute();
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
	public void afterTextChanged(Editable s) {

		searchString = searchBox.getText().toString().trim().toUpperCase();
		if(curSearchTask!=null && curSearchTask.getStatus() != AsyncTask.Status.FINISHED)
		{
			try{
				curSearchTask.cancel(true);
			}
			catch(Exception e){
				Log.i(TAG, "Fail to cancel running search task");
			}
		}
		curSearchTask = new SearchListTask();
		curSearchTask.execute(searchString); // put it in a task so that ui is not freeze
    }
    
    
    @Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
    	// do nothing
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// do nothing
	}
    
	private class SearchListTask extends AsyncTask<String, Void, String> {
		
		@Override
		protected String doInBackground(String... params) {
			filterList.clear();
			
			String keyword = params[0];
			
			inSearchMode = (keyword.length() > 0);

			if (inSearchMode) {
				// get all the items matching this
				for (SerieItemInterface item : contactList) {
					SerieItem contact = (SerieItem)item;
					
					if ((contact.getNombre().toUpperCase().indexOf(keyword) > -1) ) {
						filterList.add(item);
					}
				}
			} 
			return null;
		}
		
		protected void onPostExecute(String result) {
			
			synchronized(searchLock)
			{
				if(inSearchMode){
					SerieAdapter adapter = new SerieAdapter(ListadoSeriesActivity.this, R.layout.example_contact_item, filterList);
					adapter.setInSearchMode(true);
					listview.setInSearchMode(true);
					listview.setAdapter(adapter);
				}
				else{
					SerieAdapter adapter = new SerieAdapter(ListadoSeriesActivity.this, R.layout.example_contact_item, contactList);
					adapter.setInSearchMode(false);
					listview.setInSearchMode(false);
					listview.setAdapter(adapter);
				}
			}
		}
	}
	
	/**
	 * Background Async Task to Load all product by making HTTP Request
	 * */
	public class LoadAlphabeticSeries extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ListadoSeriesActivity.this);
			pDialog.setMessage("Cargando el listado de series.");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) {
			listaSeries.clear();
			String error = "0";
			List<NameValuePair> params;
			List<SerieItemInterface>  list = new  ArrayList<SerieItemInterface>();
			JSONObject json = new JSONObject();
			try {
				params = new ArrayList<NameValuePair>();
//				params.add(new BasicNameValuePair("comunidad", args[0]));
				json = jParser.makeHttpRequest(ComunUtilidades.URL_GET_ALL_SERIES, "GET", params);
				Log.d("Mis series: ", json.toString());
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					series = json.getJSONArray(TAG_SERIES);
					for (int i = 0; i < series.length(); i++) {
						JSONObject c = series.getJSONObject(i);
						
						int id = c.getInt(TAG_ID);
						String name = c.getString(TAG_NOMBRE);
						String desc = c.getString(TAG_DESCRIPCION);
						String pais = c.getString(TAG_PAIS);
						String fecha = c.getString(TAG_FECHA_ESTRENO);
						String fechaFin = c.getString(TAG_FECHA_FIN);
						String imagen = ComunUtilidades.SERVIDOR_IMAGENES + c.getString(TAG_IMAGEN);
						int dia = c.getInt(TAG_DIA_EMISION);
						String estado = c.getString(TAG_ESTADO);
						String temp = c.getString(TAG_TEMPORADA);
						String capi = c.getString(TAG_NUM_CAPITULOS);
						String valoracion = c.getString(TAG_VALORACION);
						
						SerieObject serie = new SerieObject(id, name, desc, pais, fecha, fechaFin, imagen, dia, estado, temp, capi, valoracion);
						listaSeries.add(serie);
						
						list.add(new SerieItem(id , name , estado , imagen) );
					}
					contactList = list;
				}
			} catch (JSONException e) {
				e.printStackTrace();
				error = "1";
			} catch (RuntimeException e) {
				e.printStackTrace();
				error = "1";
			}

			return error;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(final String error) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
			 public void run() {
				if (error.equals("0")) {
					SerieAdapter adapter = new SerieAdapter(getApplicationContext(), R.layout.example_contact_item, contactList);
					listview.setAdapter(adapter);
				} else {
					Toast.makeText(getApplicationContext(), getString(R.string.error_conexion),
							Toast.LENGTH_LONG).show();
				}
			 }
			});

		}
	}
    
}
